package com.zzyl.nursing.controller.member.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.controller.member.service.MemberOrderService;
import com.zzyl.nursing.dto.AppointmentDto;
import com.zzyl.nursing.mapper.MemberOrderMapper;
import com.zzyl.nursing.vo.AppointmentMessageVo;
import com.zzyl.nursing.vo.AppointmentVo;
import com.zzyl.nursing.vo.CountByTimeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class MemberOrderServiceImpl implements MemberOrderService{

    @Autowired
    private MemberOrderMapper memberOrderMapper;

    //1.查询取消预约数量
    @Override
    public int  getCancelledCount() {

        Long userId = UserThreadLocal.getUserId();

        //获取当天开始时间和结束时间
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        //查询当前登录用户取消预约数量
        int i= memberOrderMapper.getCancelledCountByUserId(userId ,startTime, endTime);
        return i;
    }

    //2.查询每个时间段剩余预约次数
    @Override
    public List<CountByTimeVo> getCountByTime(Long time) {
        //获取当天开始时间和结束时间

        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        return memberOrderMapper.getCountByTime(startTime,endTime);
    }
    //3.新增预约
    @Override
    public void addReservation(AppointmentDto appointmentDto) {
        appointmentDto.setUserId(UserThreadLocal.getUserId());
        appointmentDto.setCreateTime(LocalDateTime.now());
        //根据当前时间获取预约状态信息
        //1.获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 空值检查
        String timeStr = appointmentDto.getTime();
        if (timeStr == null || timeStr.trim().isEmpty()) {
            throw new IllegalArgumentException("预约时间不能为空");
        }
        LocalDateTime appointmentTime = LocalDateTime.parse(appointmentDto.getTime(),
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        if(now.isBefore(appointmentTime)){
            //预约时间大于当前时间，状态为0(待处理)
            appointmentDto.setStatus(0);
        }
        if (now.isAfter(appointmentTime)){
            //预约时间小于当前时间，状态为1(已完成)
            appointmentDto.setStatus(1);
        }
        memberOrderMapper.addReservation(appointmentDto);
    }
    // 查询预约
    public AppointmentMessageVo selectAppointment(Integer page, Integer pageSize, Integer status){
        // 分页参数处理
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1 || pageSize > 100) {
            pageSize = 10;
        }

        // 计算分页参数
        int offset = (int) ((page - 1) * pageSize);
        int limit = pageSize.intValue();

        // 查询数据列表
        List<AppointmentVo> appointmentList = memberOrderMapper.selectAppointmentList(offset, limit, status);

        // 查询总记录数
        int total = memberOrderMapper.selectAppointmentCount(status);

        // 构建返回结果
        AppointmentMessageVo result = new AppointmentMessageVo();
        result.setTotal(total);
        result.setRows(appointmentList);
        return result;
    }

    //取消预约
    public void cancelAppointment(Long id){
        //获取当前用户id
        Long userId = UserThreadLocal.getUserId();
        memberOrderMapper.deleteAppointmentById(id,userId);
    }

    // 更新预约状态
    public void changeAppointmentStatus(){
        // 根据创建人id查询预约信息
        List<AppointmentVo> appointmentList = memberOrderMapper.selectAppointmentById(UserThreadLocal.getUserId());
        // 判断预约信息是否为空
        if (appointmentList == null || appointmentList.isEmpty()) {
            return;
        }
        // 遍历预约信息
        for (AppointmentVo appointment : appointmentList) {
            LocalDateTime now = LocalDateTime.now();
            // 解析字符串时间为LocalDateTime
            LocalDateTime appointmentTime = LocalDateTime.parse(appointment.getTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            if (now.isAfter(appointmentTime)) {
                // 当前时间大于预约时间，更新预约状态为3(过期)
                appointment.setStatus(3);
                memberOrderMapper.updateAppointmentStatus(appointment);
            }
        }
    }

}
